<template>
    <el-tree
            :data="dataSource"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            @node-click="clickNode"
    >
        <template #default="{ node, data }">
                    <span class="custom-tree-node">
                      <span>{{ node.label }}</span>
                      <span>
                        <a @click="edit(node, data)">
                            <el-icon> <Edit/> </el-icon>
                        </a>
                        <a style="margin-left: 8px" @click="add(node, data)">
                            <el-icon> <Plus/> </el-icon>
                        </a>
                        <a style="margin-left: 8px" @click="remove(node, data)">
                            <el-icon color="red"> <Minus/> </el-icon>
                        </a>
                      </span>
                    </span>
        </template>
    </el-tree>


    <!-- 添加、修改    -->
    <el-dialog v-model="formBodyRef.dialogFormVisible" :title="formBodyRef.formTitle" :before-close="handleClose">
        <el-form
                ref="dataFormRef"
                :model="formData"
                :rules="rules"
                label-width="80px"
        >
            <el-form-item label="文件名称" prop="name">
                <el-input v-model.trim="formData.name"/>
            </el-form-item>

            <el-form-item label="文件类型" prop="fileTypeMsg">
                <el-select v-model="formData.fileTypeMsg" placeholder="文件类型">
                    <el-option label="文件夹" value="文件夹"/>
                    <el-option label="文件" value="文件"/>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(dataFormRef)">提交</el-button>
                <el-button @click="resetForm(dataFormRef)">撤销</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


</template>

<script setup lang="ts">
    import {ref, toRefs, unref, reactive, onMounted, onBeforeUnmount} from "vue";
    import {getFilePathTree, findFilePathById, insertFilePath, updateFilePath, deleteFilePath} from "@/api/file-path"
    import {MittEventEnum} from "@/utils/enum/mitt-event-enum"
    import emitter from "@/utils/event-bus";
    import {LoginStateEnum} from "@/utils/enum/enum";
    import {Local} from "@/utils/local";
    import {ElMessage, ElMessfileName} from "element-plus";
    import type {FormInstance, ElMessageBox} from 'element-plus'
    import {rejects} from "assert";


    // 表单处理 start
    const formBodyRef = reactive({
        dialogFormVisible: false,
        formLabelWidth: '140px',
        formTitle: '',
        formData: {
            id: undefined,
            name: undefined,
            fileTypeMsg: "文件夹",
            pid: 0
        },
        rules: {
            name: [
                {required: true, message: '文件名称不能为空！', trigger: 'blur'}
            ]
        }
    })

    const {
        dialogFormVisible,
        formTitle,
        formLabelWidth,
        rules,
        formData
    } = toRefs(formBodyRef);


    const dataFormRef = ref<FormInstance>()

    // 关闭事件
    const handleClose = (done?: () => void) => {
        formData.value.id = undefined;
        dataFormRef.value.resetFields();
        dataFormRef.value.clearValidate();
        if (done)
            done();
    }

    const submitForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.validate((valid) => {
            if (valid) {
                const id = formBodyRef.formData.id
                if (id) {
                    updateFilePath(id, formData.value)
                        .then(response => {
                            load();
                            handleClose();
                            formBodyRef.dialogFormVisible = false;
                        })
                } else {
                    insertFilePath(formData.value)
                        .then(response => {
                            formEl.resetFields()
                            formBodyRef.dialogFormVisible = false;
                            load();
                        })
                }
            } else {
                return false
            }
        })
    }

    const resetForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
    }

    // 表单处理 end

    interface Tree {
        id: number
        label: string
        children?: Tree[]
    }

    const dataSource = ref<Tree[]>([])

    const remove = (node: Node, data: Tree) => {
        if (node["childNodes"].length > 0) {
            ElMessage({
                message: '当前文件下存在子文件，无法删除！，请删除子文件！',
                type: 'error'
            })
            return;
        }
        deleteFilePath(data["id"]);
        const parent = node["parent"]
        const children: Tree[] = parent.data.children || parent.data
        const index = children.findIndex((d) => d.id === data.id)
        children.splice(index, 1)
        dataSource.value = [...dataSource.value]
    }

    // 发送点击文件节点事件，携带点击的节点信息
    const clickNode = (a: any, b: any, c: any, d: any) => {
        emitter.emit(MittEventEnum.CLICK_FILE_TREE_NODE_EVENT, a)
    }

    function load() {
        //加载文件树
        getFilePathTree().then(response => {
            if (response['code'] == 200) {
                dataSource.value = response.data;
            } else {
                ElMessage({
                    showClose: true,
                    message: response["msg"],
                    type: 'error'
                })
            }
        })
    }

    function add(data: Tree) {
        formBodyRef.dialogFormVisible = true;
        formBodyRef.formTitle = "添加文件"
        formBodyRef.formData.pid = data["data"]["id"];
    }

    function edit(data: Tree) {
        formBodyRef.dialogFormVisible = true;
        formBodyRef.formTitle = "修改文件"
        formBodyRef.formData.id = data["data"]["id"];
        findFilePathById(formBodyRef.formData.id).then(response => {
            let data = response["data"];
            formBodyRef.formData = data
        })
    }

    onMounted(() => {
        load();
    })

    // mitt监听
    emitter.on(MittEventEnum.REFRESH_FILE_TREE_EVENT, (info) => {
        console.log("----------刷新文件树------------")
        load()
    });

    onBeforeUnmount(() => {
        emitter.off(MittEventEnum.REFRESH_FILE_TREE_EVENT)
    })
</script>

<style scoped>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>